var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');
var formidable = require('formidable');

function localDate(s) {
    var d = new Date(s);
    var s = d.getFullYear() + "-";
    s += ("0" + (d.getMonth() + 1)).slice(-2) + "-";
    s += ("0" + d.getDate()).slice(-2) + " ";
    s += ("0" + d.getHours()).slice(-2) + ":";
    s += ("0" + d.getMinutes()).slice(-2) + ":";
    s += ("0" + d.getSeconds()).slice(-2);
    return s;
}

var rootDir = 'D:\\';//'/home/liuzy/fang';
var nowDir = rootDir;

function list(d) {
    var files = fs.readdirSync(d);
    var dd = [];
    var ff = [];
    for (var i = 0; i < files.length; i++) {
        if (files[i] == 'System Volume Information' || files[i] == '$RECYCLE.BIN') {
            continue;
        }
        var p = path.join(d, files[i]);
        var stat = fs.statSync(p);
        var f = {};
        f.name = files[i];
        f.mtime = localDate(stat.mtime);
        if (stat.isDirectory()) {
            f.type = '目录';
            f.href = '/?p=' + encodeURIComponent(p);
            dd.push(f);
        } else {
            f.type = '文件';
            f.href = '/d?p=' + encodeURIComponent(p);
            f.size = calcSize(stat.size);
            ff.push(f);
        }
    }
    return {
        dir: d,
        father: '/?p=' + path.join(d, '..'),
        childs: dd.concat(ff)
    };
}

function calcSize(size) {
    var byte = 0;
    var unit = ' B';
    if (size > 1024 * 1024 * 1024) {
        byte = size / 1024 / 1024 / 1024;
        unit = ' GB';
    } else if (size > 1024 * 1024) {
        byte = size / 1024 / 1024;
        unit = ' MB';
    } else if (size > 1024) {
        byte = size / 1024;
        unit = ' KB';
    } else {
        byte = size;
    }
    if (byte % 1 == 0) {
        return byte + unit;
    } else {
        return byte.toFixed(2) + unit;
    }
}

router.get('/', function(req, res, next) {
    var p = req.query.p;
    if (p == undefined || p.startsWith(rootDir) == false) {
        nowDir = rootDir;
    } else {
        nowDir = p;
    }
    res.render('index', list(nowDir));
});

router.get('/d', function(req, res, next) {
    var p = req.query.p;
    if (p) {
        fs.readFile(p, "binary", function(err, file) {
            if (err) {
                res.writeHead(500, {
                    'Content-Type': 'text/plain'
                });
                res.end(err);
            } else {
                res.setHeader('Content-Type', 'application/octet-stream');
                res.setHeader('Content-Disposition', 'attachment;fileName=' + encodeURIComponent(path.basename(p)));
                res.setHeader('Content-Length', fs.statSync(p).size);
                res.write(file, "binary");
                res.end();
            }
        });
    } else {
        res.redirect('/');
    }
});

router.post('/u', function(req, res, next) {
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.uploadDir = nowDir;
    form.parse(req, function(err, fields, files) {
        fs.renameSync(files.file.path, path.join(nowDir, files.file.name));
        res.redirect('/?p=' + nowDir);
    });
});

router.get('/c', function(req, res, next) {
    var d = req.query.d;
    if (d && d != 'null' && d != 'undefined') {
        var dd = path.join(nowDir, d);
        if (!fs.existsSync(dd)) {
            fs.mkdirSync(dd);
        }
    }
    res.render('index', list(nowDir));
});
module.exports = router;
